package com.lam.common.base.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.lam.common.base.page.TableData;
import com.lam.common.exception.BusinessException;
import com.lam.common.utils.BeanUtil;
import com.lam.common.utils.CollectionUtil;

/**
 * API 前端web层通用数据处理
 * 
 * @author lam
 */
public abstract class ApiBaseController extends BaseController{
	
	protected <T> TableData convertData(TableData tableData, Class<T> targetClass) {
		if(tableData == null) {
			return tableData;
		}
		tableData.records(convertData(tableData.getRecords(), targetClass));
		return tableData;
	}

	@SuppressWarnings("unchecked")
	protected <T> List<T> convertData(List<?> list, Class<T> targetClass) {
		
		if(CollectionUtil.isEmpty(list) || targetClass == null) {
			return Collections.emptyList();
		}
		if(list.get(0).getClass() == targetClass) {
			return (List<T>) list;
		}
		
		List<T> newList = new ArrayList<>();
		for (Object o : list) {
			newList.add(convertData(o, targetClass));
		}
		return newList;
	}
	
	protected <T> T convertData(Object o, Class<T> targetClass) {
		if(o == null) {
			return null;
		}
		try {
			T t = targetClass.newInstance();
			BeanUtil.copyProperties(o, t);
			return t;
		} catch (Exception e) {
			logger.error("转换对象数据异常", e);
			throw new BusinessException("哎呀，一不小心，系统异常啦！");
		}
	}
	
}
